<template>
  <!-- 用户详情主容器 -->
  <div class="user-detail-container">
    <!-- 用户信息卡片，使用Element Plus的el-card组件 -->
    <el-card class="user-info-card">
      <template #header>
        <div class="card-header">
          <span>用户{{ userId }}详细信息</span>
          <!-- 返回按钮，使用Element Plus的el-button组件 -->
          <el-button @click="$router.back()" type="primary" plain>
            <el-icon><Back /></el-icon>返回
          </el-button>
        </div>
      </template>

      <!-- 用户信息描述列表，使用Element Plus的el-descriptions组件 -->
      <el-descriptions :column="3" border>
        <el-descriptions-item label="用户ID">{{ userInfo.userId }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ userInfo.username }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ userInfo.age }}</el-descriptions-item>
        <el-descriptions-item label="通关分数">{{ userInfo.score }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ userInfo.completionTime }}</el-descriptions-item>
        <el-descriptions-item label="完成率">{{ userInfo.completionRate }}%</el-descriptions-item>
        <el-descriptions-item label="设备号">{{ userInfo.deviceId }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 理论知识信息统计卡片 -->
    <el-card class="knowledge-stat-card">
      <template #header>
        <div class="card-header">
          <span>理论知识信息统计</span>
        </div>
      </template>
      
      <el-descriptions :column="3" border>
        <el-descriptions-item label="总题数">{{ totalQuestions }}</el-descriptions-item>
        <el-descriptions-item label="已完成题数">{{ completedQuestions.length }}</el-descriptions-item>
        <el-descriptions-item label="错题数">{{ incorrectQuestions.length }}</el-descriptions-item>
        <el-descriptions-item label="完成度">
          <el-progress :percentage="Number(knowledgeStats.completionRate)" :format="() => `${knowledgeStats.completionRate}%`" />
        </el-descriptions-item>
        <el-descriptions-item label="正确率">
          <el-progress :percentage="Number(knowledgeStats.accuracyRate)" :format="() => `${knowledgeStats.accuracyRate}%`" status="success" />
        </el-descriptions-item>
        <el-descriptions-item label="错题编号">
          {{ incorrectQuestions.length ? incorrectQuestions.join(', ') : '无' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 能力分布图卡片 -->
    <el-card class="ability-chart-card">
      <template #header>
        <div class="card-header">
          <span>能力分布图</span>
        </div>
      </template>
      <!-- ECharts图表容器 -->
      <div id="ability-radar-chart" class="chart-container"></div>
    </el-card>
  </div>
</template>

<script setup>
// 导入Vue相关API
import { ref, onMounted, onUnmounted } from 'vue'
// 导入Vue Router的useRoute钩子
import { useRoute } from 'vue-router'
// 导入ECharts图表库
import * as echarts from 'echarts'
import axios from 'axios'
import { API_BASE_URL } from '@/utils/constants'

// 获取当前路由信息
const route = useRoute()
// 从路由参数中获取用户ID
const userId = route.params.id

// 用户信息响应式数据
const userInfo = ref({
  id: '',
  name: '',
  age: 0,
  score: 0,
  completionTime: '',
  completionRate: 0,
  deviceId: ''
})

// 将原有的5维能力数据修改为3维
const abilityData = ref({
  operationSkill: 0,    // 操作熟练度
  theoreticalKnowledge: 0, // 理论知识
  averageGameDuration: 0   // 新增：平均游戏时长（单位：秒）
})

// 新增响应式数据
const totalQuestions = ref(0) // 总题数
const completedQuestions = ref([]) // 已完成题数组
const incorrectQuestions = ref([]) // 错题数组
const knowledgeStats = ref({
  completionRate: 0, // 完成度
  accuracyRate: 0    // 正确率
})

// 雷达图实例变量
let radarChart = null

/**
 * 初始化雷达图
 * 使用ECharts库创建雷达图展示用户能力分布
 */
const initRadarChart = () => {
  const chartDom = document.getElementById('ability-radar-chart')
  radarChart = echarts.init(chartDom)

  const option = {
    title: {
      text: '用户能力分布',
      left: 'center'
    },
    radar: {
      indicator: [
        { name: '操作熟练度', max: 100 },
        { name: '理论知识', max: 100 },
        { 
          name: '平均游戏时长(秒)', 
          max: 3600,
          // 解决刻度可读性问题的关键配置
          splitNumber: 6,      // 明确指定分割段数
          interval: 600,       // 每600秒(10分钟)一个刻度
          axisLabel: {
            formatter: (value) => {
              // 将秒转换为分钟显示，提高可读性
              return value >= 60 ? `${(value/60).toFixed(1)}分钟` : `${value}秒`
            }
          }
        }
      ],
      shape: 'polygon',
      splitNumber: 5,
      // 明确关闭alignTicks（如果不需要多轴对齐）
      alignTicks: false,
      axisName: {
        color: '#333'
      },
      splitArea: {
        areaStyle: {
          color: ['#f3f6f9', '#e9ecf2']
        }
      }
    },
    series: [{
      name: '能力评估',
      type: 'radar',
      data: [{
        value: [
          abilityData.value.operationSkill,
          abilityData.value.theoreticalKnowledge,
          abilityData.value.averageGameDuration
        ],
        name: '能力评估',
        areaStyle: {
          color: 'rgba(64,158,255,0.2)'
        },
        lineStyle: {
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF'
        }
      }]
    }]
  }

  radarChart.setOption(option)
}

/**
 * 获取用户详细信息
 * 模拟API请求获取用户数据
 */
const fetchUserDetail = async () => {
  try {
    const res = await axios.get(`${API_BASE_URL}/user/${userId}`)
    userInfo.value = res.data.data
    
  } catch (error) {
    console.error('获取用户详情失败:', error)
  }
}

// 获取用户能力数据
const fetchcahrtdata = async () => {
  try {
    const res = await axios.get(`${API_BASE_URL}/gamepass/allscore/${userId}`)
    const res1 = await axios.get(`${API_BASE_URL}/gamepass/${userId}`)
    // console.log('aaaaa',res)
    abilityData.value.operationSkill = res.data.data / res1.data.data.length 
    // abilityData.value.averageGameDuration = res.data.data / res.data.data.length
    abilityData.value.theoreticalKnowledge =knowledgeStats.value.completionRate
    const res2 = await axios.get(`${API_BASE_URL}/gamepass/${userId}`)
    console.log('bbbbb',res2)    
    res2.data.data.forEach(item => {
      console.log('item',item)
      abilityData.value.averageGameDuration += item.seconds
    })
    abilityData.value.averageGameDuration /= res2.data.data.length
    console.log('ccccc',abilityData.value.averageGameDuration)

  } catch (error) {
    console.error('获取用户能力数据失败:', error)
  }
    initRadarChart()
}

/**
 * 获取题目总数
 */
const fetchTotalQuestions = async () => {
  try {
    const res = await axios.get(`${API_BASE_URL}/knowledge-contents/count/questions`)
    if (res.data.code === 1) {
      totalQuestions.value = res.data.data
    }
  } catch (error) {
    console.error('获取题目总数失败:', error)
  }
}

/**
 * 获取答题记录
 */
const fetchAnswerRecord = async () => {
  try {
    // 添加userId查询参数确保获取指定用户数据
    const res = await axios.get(`${API_BASE_URL}/answer-questions/${userId}`)
    console.log(res)
    if (res.data.code === 1 && res.data.data) {
      const data = res.data.data
      completedQuestions.value = JSON.parse(data.completedQuestions || '[]')
      incorrectQuestions.value = JSON.parse(data.incorrectQuestions || '[]')
      
      // 计算统计指标
      const completedCount = completedQuestions.value.length
      const incorrectCount = incorrectQuestions.value.length
      
      knowledgeStats.value.completionRate = totalQuestions.value 
        ? ((completedCount / totalQuestions.value) * 100).toFixed(1) 
        : 0
        
      knowledgeStats.value.accuracyRate = completedCount 
        ? (((completedCount - incorrectCount) / completedCount) * 100).toFixed(1) 
        : 0
    }
  } catch (error) {
    console.error('获取答题记录失败:', error)
  }
}

// 组件挂载后执行
onMounted(() => {
  // 获取用户详情数据
  fetchUserDetail()
  fetchTotalQuestions()  // 获取题目总数
  fetchAnswerRecord()    // 获取答题记录
  fetchcahrtdata()

  
  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', () => {
    radarChart?.resize()
  })
})

// 组件卸载前执行
onUnmounted(() => {
  // 销毁图表实例
  radarChart?.dispose()
  // 移除窗口大小变化监听
  window.removeEventListener('resize', () => {
    radarChart?.resize()
  })
})
</script>

<style scoped>
/* 用户详情主容器样式 */
.user-detail-container {
  padding: 20px;
}

/* 用户信息卡片和能力图表卡片样式 */
.user-info-card,
.ability-chart-card,
.knowledge-stat-card {
  margin-bottom: 20px;
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 图表容器样式 */
.chart-container {
  height: 400px;
  width: 100%;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .el-descriptions {
    flex-direction: column;
  }
  .el-descriptions-item__label {
    width: 100% !important;
    text-align: left;
  }
  .el-descriptions-item__content {
    padding-left: 0 !important;
  }
}
</style>